﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Web.UI.HtmlControls;

using Chaks.SharePoint.Docs.ILP.Utilities;

namespace Chaks.SharePoint.Docs.ILP
{
    public partial class ILPSettings : Page
    {
        #region Variables

        protected HtmlAnchor lnkListName;
        protected Button BtnSave;
        protected Button BtnCancel;
        protected RadioButton ILPEnableYes;
        protected RadioButton ILPEnableNo;
        protected PeopleEditor pplEditor;
        protected DropDownList ddlPermissionSets;
        protected RadioButton ApplyToAllYes;
        protected RadioButton ApplyToAllNo;

        private const string EventReceiverAssembly = "Chaks.SharePoint.Docs.ILP, Version=1.1.0.0, Culture=neutral, PublicKeyToken=5e4a77ec46c0cc45";
        private const string EventReceiverClass = "Chaks.SharePoint.Docs.ILP.EventReceivers.DocumentLibraryEventReceiver";

        private const string JobResetRoleInheritanceName = "ILP_RoleInheritance";

        #endregion

        #region Properties

        /// <summary>
        /// Gets the list id.
        /// </summary>
        /// <value>The list id.</value>
        private string ListId
        {
            get
            {
                return Request.QueryString["List"];
            }
        }

        /// <summary>
        /// Gets the selected list.
        /// </summary>
        /// <value>The selected list.</value>
        private SPList SelectedList
        {
            get
            { 
                return SPContext.Current.Web.Lists.GetList(new Guid(ListId), false);
            }
        }

        /// <summary>
        /// Gets the root web.
        /// </summary>
        /// <value>The root web.</value>
        private SPWeb RootWeb
        {
            get
            {
                return SPContext.Current.Site.RootWeb;
            }
        }

        #endregion
        
        #region Private Methods
        

        /// <summary>
        /// Sets the ILP values.
        /// </summary>
        private void SetILPValues()
        {
            SPWeb curWeb = SPContext.Current.Web;

            foreach (SPRoleDefinition roleDefinition in curWeb.RoleDefinitions)
            {
                ddlPermissionSets.Items.Add(roleDefinition.Name);
            }

            if (RootWeb.ILPExists(ListId))
            {
                ILPSetItem ilpListItem = RootWeb.GetILPSetItem(ListId);
                
                if (ilpListItem.EnableILP)
                {
                    ILPEnableYes.Checked = true;

                    ListItem permissionItem = ddlPermissionSets.Items.FindByValue(ilpListItem.PermissionLevel);
                    
                    if (permissionItem != null)
                    {
                        ddlPermissionSets.SelectedIndex = ddlPermissionSets.Items.IndexOf(permissionItem);
                    }
                    else
                    {
                        ddlPermissionSets.SelectedIndex = 0;
                    }

                    if (ilpListItem.Groups != "NIL")
                    {
                        pplEditor.CommaSeparatedAccounts = ilpListItem.Groups;
                    }
                }
                else
                {
                    ILPEnableNo.Checked = true;
                    ddlPermissionSets.SelectedIndex = 0;
                }

            }
            else
            {
                ILPEnableNo.Checked = true;
            }
        }

        /// <summary>
        /// Sets the name of the list.
        /// </summary>
        private void SetListName()
        {
            SPList curList = SelectedList;

            lnkListName.InnerText = curList.Title;
            lnkListName.HRef = SelectedList.DefaultViewUrl;
        }
        
        #endregion

        #region Event Handlers

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                lnkListName = FindControlRecursive(Master, "lnkListName") as HtmlAnchor;
                ILPEnableYes = FindControlRecursive(Master, "ILPEnableYes") as RadioButton;
                ILPEnableNo = FindControlRecursive(Master, "ILPEnableNo") as RadioButton;
                pplEditor = FindControlRecursive(Master, "pplEditor") as PeopleEditor;
                BtnCancel = FindControlRecursive(Master, "BtnCancel") as Button;
                BtnSave = FindControlRecursive(Master, "BtnSave") as Button;
                ApplyToAllYes = FindControlRecursive(Master, "ApplyToAllYes") as RadioButton;
                ApplyToAllNo = FindControlRecursive(Master, "ApplyToAllYes") as RadioButton;
                ddlPermissionSets = FindControlRecursive(Master, "ddlPermissionSets") as DropDownList;

                ddlPermissionSets.SelectedIndex = 0;

                SetListName();

                SetILPValues();

                BtnSave.Click += BtnSave_Click;

                BtnCancel.Attributes.Add("onClick", "javascript:history.back(); return false;");
            }
        }

        /// <summary>
        /// Handles the Click event of the BtnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void BtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                SPWeb spWeb = SelectedList.ParentWeb;

                ItemLevelPermissionSettings ilpSettings=new ItemLevelPermissionSettings();
                if(ILPEnableYes.Checked)
                {
                    ilpSettings.EnableItemLevelPermissions = true;   
                }
                else if(ILPEnableNo.Checked)
                {
                    ilpSettings.EnableItemLevelPermissions = false;
                }
                
                ilpSettings.DefaultPermissionLevel = spWeb.RoleDefinitions[ddlPermissionSets.SelectedValue];

                ilpSettings.DefaultGroups=new List<SPGroup>();
                foreach (string group in pplEditor.CommaSeparatedAccounts.Split(','))
                {
                    // get a reference to the Sharepoint group collection
                    SPGroup spGroup = spWeb.SiteGroups.Cast<SPGroup>().FirstOrDefault(g => g.Name == group);

                    if(spGroup!=null)
                    {
                        ilpSettings.DefaultGroups.Add(spGroup);
                    }
                }

                if (ApplyToAllYes.Checked)
                {
                    ilpSettings.ApplyToExistingItems = true;
                }
                else if(ApplyToAllNo.Checked)
                {
                    ilpSettings.ApplyToExistingItems = false;
                }

                ilpSettings.EventReceiverAssembly = EventReceiverAssembly;

                ilpSettings.EventReceiverClass = EventReceiverClass;

                SelectedList.EnableItemLevelPermissions(ilpSettings);

                SPUtility.Redirect("/_layouts/listedit.aspx?List=" + ListId, SPRedirectFlags.Default, HttpContext.Current);
            }
            catch (Exception exception)
            {

                throw new SPException(exception.ToString());
            }
            
        }

        #endregion

        #region Helper Methods

        /// <summary>
        /// Finds the control recursive.
        /// </summary>
        /// <param name="Root">The root.</param>
        /// <param name="Id">The id.</param>
        /// <returns></returns>
        public static Control FindControlRecursive(Control Root, string Id)
        {
            if (Root.ID == Id)
            {
                return Root;
            }

            foreach (Control Ctl in Root.Controls)
            {
                Control FoundCtl = FindControlRecursive(Ctl, Id);
                if (FoundCtl != null)
                {
                    return FoundCtl;
                }
            }

            return null;
        }

        #endregion
    }
}
